/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Left *Node
 *     Right *Node
 *     Next *Node
 * }
 */

func connect(root *Node) *Node {
	res := [][]*Node{}
    if root == nil {
        return root
    }

    queue := list.New()
    queue.PushBack(root)
    tempArr := []*Node{}
    
    for queue.Len() > 0 {
        length := queue.Len()

        for i:=0; i<length; i++ {
            node := queue.Remove(queue.Front()).(*Node)
            tempArr = append(tempArr, node)
            if node.Left != nil {
                queue.PushBack(node.Left)
            }
            if node.Right != nil {
                queue.PushBack(node.Right)
            }
        }
        res = append(res, tempArr)
        tempArr = []*Node{}
    }

    for i:=0; i<len(res); i++ {
        for j:=0; j<len(res[i])-1; j++ {
            res[i][j].Next = res[i][j+1]
        }
    }
    return root
}